package com.project.server;

import java.io.*;

/**
 * 处理响应信息
 */
public class Response {

    private OutputStream out;
    public Response(OutputStream out) {
        this.out = out;
    }
    /**
     * 发送文本数据到客户端
     *
     * @param info 文本数据
     */
    public void sendMessage(String info) {
        try {
            out.write(info.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 发送文件到客户端
     *
     * @param filePath 文件路径
     */
    public void sendFile(String filePath) {
        File file = new File(filePath);
        //文件不存在时跳出方法
        if (!file.exists()) {
            return;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] by = new byte[1024];
            int len = 0;
            //将读取的数据 去到字节数组，返回当前读取的字节
            while ((len = in.read(by)) != -1) {
                out.write(by, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
